package LockTest;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {
    private final static Logger logger = LoggerFactory.getLogger(SemaphoreTest.class);

    @Test
    public void test() throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        new Thread(() -> {
            logger.info("threadA start");
            try {
                semaphore.acquire();
                logger.info("threadA get semaphore");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
            logger.info("threadA end");
        }).start();
        new Thread(() -> {
            logger.info("threadB start");
            try {
                semaphore.acquire();
                logger.info("threadB get semaphore");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
            logger.info("threadB end");
        }).start();
        TimeUnit.SECONDS.sleep(4);
    }
}
